#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

enum
{
    SocketErr = 2,
    BindErr,
    ListenErr,
};

static const int backlog=10;

class Sock
{
public:
    Sock()
    {}

    ~Sock()
    {}

public:
    void Socket() //创建套接字
    {
        //IPV4 TCP流 默认协议
        _sockfd=socket(AF_INET,SOCK_STREAM,0);
        if(_sockfd<0)
        {
            lg(Fatal,"socket create error, %s: %d",strerror(errno),errno);
            exit(SocketErr);
        }
    }

    void Bind(uint16_t port) //绑定套接字
    {
        //填写sockaddr_in结构体
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_port=htons(port);
        local.sin_addr.s_addr=INADDR_ANY;

        //绑定套接字
        if(bind(_sockfd,(struct sockaddr*)&local, sizeof(local))<0)
        {
            lg(Fatal,"socket bind error, %s: %d",strerror(errno),errno);
            exit(BindErr);
        }
    }

    void Listen() //监听套接字
    {
        //开始监听并且设置套接字最大监听数
        if(listen(_sockfd,backlog)<0) 
        {
            lg(Fatal,"socket listen error, %s: %d",strerror(errno),errno);
            exit(ListenErr);
        }
    }

    int Accept(std::string *clientip, uint16_t *clientport) //接受套接字
    {
        //服务端来接受客户端的套接字
        struct sockaddr_in peer;
        socklen_t len=sizeof(peer);
        int newfd=accept(_sockfd,(struct sockaddr*)&peer,&len);
        if(newfd<0)
        {
            lg(Warning,"socket accept error, %s: %d",strerror(errno),errno);
            return -1;
        }
        char ipstr[64];
        inet_ntop(AF_INET,&peer.sin_addr,ipstr,sizeof(ipstr));
        *clientip=ipstr;
        *clientport=ntohs(peer.sin_port);

        return newfd;
    }

    bool Connect(const std::string &ip, const uint16_t &port) //连接套接字
    {
        //服务端请求连接客户端的套接字        
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &(peer.sin_addr));

        int n=connect(_sockfd, (struct sockaddr*)&peer, sizeof(peer));
        if(n == -1) 
        {
            std::cerr<<"connect to "<<ip<<":"<<port<<" error"<<std::endl;
            return false;
        }

        return true;
    }

    void Close() //关闭套接字
    {
        close(_sockfd);
    }

    int Fd() //返回文件描述符
    {
        return _sockfd;
    }

private:
    int _sockfd; //套接字文件描述符
};